﻿using System;
using System.Drawing;
using System.Threading;

namespace Nextensions.WinApi
{
    public class MouseMover
    {
        public delegate void FinishedHandler(Point Location);
        private const int SleepTime = 0;

        public MouseMover(Point End, FinishedHandler Finished)
        {
            PointF cur = WindowHelper.GetCursorPos();
            float xOff;// = (int)((End.X - cur.X) * 0.01);
            float yOff;// = (int)((End.Y - cur.Y) * 0.01);

            float xDistance = End.X - cur.X;
            float yDistance = End.Y - cur.Y;

            if (xDistance > yDistance)
            {
                xOff = Math.Abs(xDistance) / xDistance;
                yOff = yDistance / Math.Abs(xDistance);
            }
            else
            {
                yOff = Math.Abs(yDistance) / yDistance;
                xOff = xDistance / Math.Abs(yDistance);
            }

            System.Diagnostics.Debug.WriteLine(System.String.Format("Mouse destination {0}", End));

            while(Math.Round(cur.X) != End.X || Math.Round(cur.Y) != End.Y)
            {
                cur.X += xOff;
                cur.Y += yOff;

                Thread.Sleep(SleepTime);
                System.Diagnostics.Debug.WriteLine(System.String.Format("Moving mouse to {0}", cur));

                WindowHelper.SetCursorPos(new Point((int)cur.X, (int)cur.Y));
            }

            Finished.Invoke(new Point((int)cur.X, (int)cur.Y));
        }
    }
}
